package r25.settings;

import java.io.File;
import java.io.InputStream;
import java.util.Map;

import org.slf4j.Logger;

import r25.ServiceFactory;
import r25.tools.JsonHelper;
import r25.tools.LoggerHelper;
import r25.tools.StreamHelper;

public class SettingsManager {
	private static final Logger logger = LoggerHelper.getLogger();
	private static final String USER_HOME_PROPERTY = "user.home";
	private static final String PACKAGED_CONF = "/default-configuration.json";
	private static final String DATA_KEY = "data";

	private static final String DEPLOYED_CONF = ".r25-configuration.json";
	private static final String DEPLOYED_DATA = ".r25-data.json";

	public static void standalone() throws Exception {
		InputStream isc = SettingsManager.class
				.getResourceAsStream(PACKAGED_CONF);
		ServiceFactory.getInstance().configure(isc);
	}

	public static void deploy() throws Exception {
		String userDir = System.getProperty(USER_HOME_PROPERTY);
		logger.debug("{}", userDir);

		InputStream isc = SettingsManager.class
				.getResourceAsStream(PACKAGED_CONF);
		Map<String, Object> settings = JsonHelper.loadJson(isc);

		InputStream isw = SettingsManager.class
				.getResourceAsStream((String) settings.get(DATA_KEY));
		File deployed7w = new File(userDir, DEPLOYED_DATA);
		StreamHelper.inputStreamToFile(isw, deployed7w);

		settings.put(DATA_KEY, deployed7w.getAbsolutePath());
		File deployedConf = new File(userDir, DEPLOYED_CONF);
		JsonHelper.saveJson(deployedConf, settings);

		load();
	}

	public static void undeploy() {
		String userDir = System.getProperty(USER_HOME_PROPERTY);

		new File(userDir, DEPLOYED_CONF).delete();
		new File(userDir, DEPLOYED_DATA).delete();
	}

	public static void load() throws Exception {
		String userDir = System.getProperty(USER_HOME_PROPERTY);
		File deployedConf = new File(userDir, DEPLOYED_CONF);
		ServiceFactory.getInstance().configure(deployedConf.getAbsolutePath());
	}
}
